<template>
    <div class="addr-list">
        <div class="addr-oper-btn">
            <el-button type="primary" @click="addAddrDialog = true">新增收货地址</el-button>
        </div>

        <div class="addr-table-list">
            <!-- 编辑和删除 -->
            <el-table :data="addressTableList" :loading="addressTableLoading" style="width: 100%"
                v-if="mode === 'editAndDelete'">
                <el-table-column prop="create_time" label="创建日期" width="150">
                    <template slot-scope="scope">
                        <span>
                            {{
                                scope.row.create_time | dateFormat("yyyy-mm-dd")
                            }}
                        </span>
                    </template>
                </el-table-column>

                <el-table-column label="收货信息">
                    <el-table-column prop="receiver" label="收货人" show-overflow-tooltip width="120">
                    </el-table-column>

                    <el-table-column label="收货地址">
                        <el-table-column prop="location" label="省市县" show-overflow-tooltip width="150">
                        </el-table-column>

                        <el-table-column prop="full_addr" label="详细地址" show-overflow-tooltip width="290">
                        </el-table-column>

                        <el-table-column prop="phone" label="电话号码" show-overflow-tooltip width="133">
                        </el-table-column>
                    </el-table-column>
                </el-table-column>

                <el-table-column label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button type="warning" style="margin-left: 10px;"
                            @click="openModifyDialog(scope.row.addr_id)">编辑</el-button>
                        <el-button type="danger" style="margin-left: 10px;"
                            @click="handleDeleteAddr(scope.row.addr_id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 选择 -->
            <el-table :data="addressTableList" :loading="addressTableLoading" style="width: 100%" v-else>
                <el-table-column prop="create_time" label="创建日期" width="150">
                    <template slot-scope="scope">
                        <span>
                            {{
                                scope.row.create_time | dateFormat("yyyy-mm-dd")
                            }}
                        </span>
                    </template>
                </el-table-column>

                <el-table-column label="收货信息">
                    <el-table-column prop="receiver" label="收货人" show-overflow-tooltip width="120">
                    </el-table-column>

                    <el-table-column label="收货地址">
                        <el-table-column prop="location" label="省市县" show-overflow-tooltip width="150">
                        </el-table-column>

                        <el-table-column prop="full_addr" label="详细地址" show-overflow-tooltip width="340">
                        </el-table-column>

                        <el-table-column prop="phone" label="电话号码" show-overflow-tooltip width="133">
                        </el-table-column>
                    </el-table-column>
                </el-table-column>

                <el-table-column label="操作" width="150">
                    <template slot-scope="scope">
                        <el-button type="primary" @click="handleChoose(scope.row.addr_id)">选择</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="queryAddrTableList" />

            <div style="text-align: right;" v-if="mode === 'choose'">
                <el-button style="display: inline-block;" type="success" @click="handleSubmitOrder()">提交订单</el-button>
            </div>
        </div>

        <!-- 新增收货地址对话框 -->
        <el-dialog :append-to-body="true" :close-on-click-modal="false" :close-on-press-escape="false" title="新增收货地址"
            :visible.sync="addAddrDialog" center @close="handleAddAddrDialogClose()">

            <el-form :label-position="right" label-width="80px" ref="addAddrForm" :model="addAddrForm"
                :rules="addAddrRules">
                <el-form-item label="收货人" prop="receiver">
                    <el-input v-model="addAddrForm.receiver" maxlength="10"></el-input>
                </el-form-item>
                <el-form-item label="电话号码" prop="phone">
                    <el-input v-model="addAddrForm.phone" maxlength="15"></el-input>
                </el-form-item>
                <el-form-item label="省市县" prop="location">
                    <el-cascader size="medium" :options="locations" v-model="addAddrForm.location" placeholder="请选择省市县">
                    </el-cascader>
                </el-form-item>
                <el-form-item label="详细地址" prop="full_addr">
                    <el-input v-model="addAddrForm.full_addr" maxlength="150"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button style="width: 200px; font-size: 17px;" type="primary" @click="handleAddAddr()"
                    :loading="isAddingAddr">添加</el-button>
            </span>
        </el-dialog>

        <!-- 编辑收货地址对话框 -->
        <el-dialog :append-to-body="true" :close-on-click-modal="false" :close-on-press-escape="false" title="编辑收货地址"
            :visible.sync="modifyAddrDialog" center @close="handleModifyAddrDialogClose()">

            <el-form :label-position="right" label-width="80px" ref="modifyAddrForm" :model="modifyAddrForm"
                :rules="modifyAddrRules">
                <input v-model="modifyAddrForm.addr_id" type="hidden" />
                <el-form-item label="收货人" prop="receiver">
                    <el-input v-model="modifyAddrForm.receiver" maxlength="10"></el-input>
                </el-form-item>
                <el-form-item label="电话号码" prop="phone">
                    <el-input v-model="modifyAddrForm.phone" maxlength="15"></el-input>
                </el-form-item>
                <el-form-item label="省市县" prop="location">
                    <el-cascader size="medium" :options="locations" v-model="modifyAddrForm.location" placeholder="请选择省市县">
                    </el-cascader>
                </el-form-item>
                <el-form-item label="详细地址" prop="full_addr">
                    <el-input v-model="modifyAddrForm.full_addr" maxlength="150"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button style="width: 200px; font-size: 17px;" type="primary" @click="handleModifyAddr()"
                    :loading="isModifyingAddr">修改</el-button>
            </span>

        </el-dialog>
    </div>
</template>

<script>
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
import { queryAddressTableList, createAddress, queryModifyAddrForm, modifyAddress, deleteAddr } from '@/api/addr'
import { verifyPhoneIsValid } from '@/utils/tool'

export default {
    name: 'AddrList',

    props: ['mode'],

    data() {
        return {
            addressTableList: null,
            addressTableLoading: false,
            queryParams: {
                pageNum: 1,
                pageSize: 5,
            },
            total: 0,

            addressTableList: null,
            addressTableLoading: false,
            queryParams: {
                pageNum: 1,
                pageSize: 5,
            },
            total: 0,

            addAddrDialog: false,
            addAddrForm: {
                receiver: '',
                phone: '',
                location: [],
                full_addr: ''
            },
            addAddrRules: {
                receiver: [
                    { required: true, message: '请输入收货人名称', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入收货人电话号码', trigger: 'blur' }
                ],
                location: [
                    { type: 'array', required: true, message: '请选择省市县', trigger: 'change' }
                ],
                full_addr: [
                    { required: true, message: '请输入收货详细地址', trigger: 'blur' }
                ],
            },

            locations: regionData,
            isAddingAddr: false,

            modifyAddrDialog: false,
            modifyAddrForm: {
                addr_id: 0,
                receiver: '',
                phone: '',
                location: [],
                full_addr: ''
            },
            modifyAddrRules: {
                receiver: [
                    { required: true, message: '请输入收货人名称', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入收货人电话号码', trigger: 'blur' }
                ],
                location: [
                    { type: 'array', required: true, message: '请选择省市县', trigger: 'change' }
                ],
                full_addr: [
                    { required: true, message: '请输入收货详细地址', trigger: 'blur' }
                ],
            },

            isModifyingAddr: false,
        }
    },

    created() {
        this.openManageAddrDialog()
    },

    methods: {
        queryAddrTableList() {
            this.addressTableLoading = true
            queryAddressTableList(this.queryParams).then((res) => {
                if (res.code === 200) {
                    this.addressTableList = res.rows
                    this.addressTableLoading = false
                    this.total = res.total;
                }
            })
        },

        openManageAddrDialog() {
            this.manageAddrDialog = true
            this.queryAddrTableList()
        },


        // 添加收货地址
        handleAddAddr() {
            this.$refs.addAddrForm.validate((valid) => {
                if (valid) {
                    if (!verifyPhoneIsValid(this.addAddrForm.phone)) {
                        this.$message.error('不是中国大陆手机号码')
                        return false
                    }

                    this.isAddingAddr = true

                    let locationArr = this.addAddrForm.location

                    let location = ''

                    for (let i = 0; i < locationArr.length; i++) {
                        if (i === 0) {
                            location += CodeToText[locationArr[i]]
                        } else {
                            location += '/' + CodeToText[locationArr[i]]
                        }
                    }

                    let receiver = this.addAddrForm.receiver
                    let phone = this.addAddrForm.phone
                    let full_addr = this.addAddrForm.full_addr
                    createAddress(receiver, phone, location, full_addr).then((res) => {
                        if (res.code === 200) {
                            this.$message.success(res.msg)
                            this.addAddrDialog = false
                            this.queryAddrTableList()
                        }
                    })
                    this.isAddingAddr = false
                } else {
                    return false;
                }
            })
        },

        handleAddAddrDialogClose() {
            this.$refs.addAddrForm.resetFields();
        },

        // 编辑收货地址
        openModifyDialog(addrId) {

            // 获取收货地址表单
            queryModifyAddrForm(addrId).then((res) => {
                if (res.code === 200) {
                    let item = res.data

                    this.modifyAddrForm.addr_id = item.addr_id
                    this.modifyAddrForm.receiver = item.receiver
                    this.modifyAddrForm.phone = item.phone
                    this.modifyAddrForm.full_addr = item.full_addr

                    let locationArr = item.location.split('/')
                    this.modifyAddrForm.location[0] = TextToCode[locationArr[0]].code
                    this.modifyAddrForm.location[1] = TextToCode[locationArr[0]][locationArr[1]].code
                    this.modifyAddrForm.location[2] = TextToCode[locationArr[0]][locationArr[1]][locationArr[2]].code

                    this.modifyAddrDialog = true
                }
            })
        },

        handleModifyAddr() {
            this.$refs.modifyAddrForm.validate((valid) => {
                if (valid) {
                    if (!verifyPhoneIsValid(this.modifyAddrForm.phone)) {
                        this.$message.error('不是中国大陆手机号码')
                        return false
                    }

                    this.isModifyingAddr = true

                    let locationArr = this.modifyAddrForm.location

                    let location = ''

                    for (let i = 0; i < locationArr.length; i++) {
                        if (i === 0) {
                            location += CodeToText[locationArr[i]]
                        } else {
                            location += '/' + CodeToText[locationArr[i]]
                        }
                    }

                    let addr_id = this.modifyAddrForm.addr_id
                    let receiver = this.modifyAddrForm.receiver
                    let phone = this.modifyAddrForm.phone
                    let full_addr = this.modifyAddrForm.full_addr
                    modifyAddress(addr_id, receiver, phone, location, full_addr).then((res) => {
                        if (res.code === 200) {
                            this.$message.success(res.msg)
                            this.modifyAddrDialog = false
                            this.queryAddrTableList()
                        }
                    })

                    this.isModifyingAddr = false
                } else {
                    return false;
                }
            })
        },

        handleModifyAddrDialogClose() {
            this.$refs.modifyAddrForm.resetFields();
        },

        handleDeleteAddr(addrId) {
            this.$confirm('此操作将永久删除该地址, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteAddr(addrId).then((res) => {
                    if (res) {
                        this.$message.success('删除成功!')
                        this.queryAddrTableList()
                    }
                })
            })
        },

        handleChoose(addrId) {
            this.$emit('handleChooseAddr', addrId)
        },

        handleSubmitOrder() {
            this.$emit('submitOrder')
        }
    }

}

</script>

<style scope>
.addr-oper-btn {
    margin-bottom: 30px;
}
</style>